#include"heap.h"
void Heapinit(HP* root)
{
	assert(root);
	root->a = NULL;
	root->capacity = 0;
	root->size = 0;
}
void Heapdestroy(HP* root)
{
	assert(root);
	free(root->a);
	root->a = NULL;
	root->capacity = root->size = 0;
}

void Swap(int* a, int* b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}
void AdjustUp(typedata* a, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[parent] <a[child])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void AdjustDown(typedata* a,int n, int parent)
{
	int child = 2 * parent + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child] < a[child + 1])
		{
			++child;
		}
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = 2 * parent + 1;

		}
		else
		{
			break;
		}
	}
}
void Heappush(HP* root, typedata x)
{
	assert(root);
	if (root->capacity == root->size)
	{
		int newcapacity = root->capacity == 0 ? 4 : 2 * root->capacity;
		int* tmp = (typedata*)realloc(root->a, newcapacity*sizeof(typedata));
		if (tmp == NULL)
		{
			perror("malloc fail");
			return;
		}
		root->a = tmp;
		root->capacity = newcapacity;

	}
	root->a[root->size] = x;
	root->size++;

	AdjustUp(root->a,root->size-1);

}
void Heappop(HP* root)
{
	assert(root);

	Swap(&root->a[0], &root->a[root->size - 1]);
	root->size--;
	AdjustDown(root->a, root->size, 0);
}
bool Heapempty(HP* root)
{
	assert(root);
	return root->size == 0;
}
typedata Heaptop(HP* root)
{
	assert(root);
	assert(!Heapempty(root));

	return root->a[0];
}

typedata Heapsize(HP* root)
{
	assert(root);
	return root->size;
}